package main

import (
	"fmt"
	"strconv"
	"strings"

	"github.com/samber/mo"
	log "github.com/sirupsen/logrus"
	"gopkg.in/pygz/subprocess.v1"
)

func MysqlDump(node Node) mo.Result[string] {
	ctx := log.WithFields(log.Fields{
		"host": node.Host,
		"name": node.Name,
	})
	command := make([]string, 0)
	command = append(command, config.Command...)
	for idx, ele := range command {
		ele = strings.ReplaceAll(ele, "{host}", node.Host)
		ele = strings.ReplaceAll(ele, "{password}", node.Password)
		ele = strings.ReplaceAll(ele, "{user}", node.User)
		ele = strings.ReplaceAll(ele, "{name}", node.Name)
		ele = strings.ReplaceAll(ele, "{port}", strconv.Itoa(node.Port))
		command[idx] = ele
	}
	// log.Info("execute: ", strings.Join(command, " "))
	resp := subprocess.Run(command[0], command[1:]...)
	if resp.ExitCode != 0 {
		ctx.WithFields(log.Fields{
			"error": resp.StdErr,
		}).Error("dump database fail")
		return mo.Err[string](fmt.Errorf("process exit code: %d", resp.ExitCode))
	}
	ctx.Info("dump database success")
	return mo.Ok(resp.StdOut)
}
